from django.http import HttpResponse
from app.models.ucode import Ucodes
# 引入result.py中定义的数据类型转换工具类和方法
from app.util.result import model_to_dict, CodeModeDTO
from django.views.decorators.http import require_http_methods
from django.views.decorators.csrf import csrf_exempt
import datetime


@require_http_methods(["POST", "GET"])
# 屏蔽csrf保护
@csrf_exempt
def query_by_ucode(request):
    """
    根据ucode值，查找用户uid 和 oid
    :param request: 数据请求
    :return: json
    """
    ucode = request.GET.get('ucode', "")
    if ucode == "":
        user_json = CodeModeDTO(CodeModeDTO.PARAMETER_ERROR, '缺少参数', '')
        return HttpResponse(user_json.to_json(), content_type='application/json,charset=utf-8')
    try:
        uids = Ucodes.objects.get(u_code=ucode)
        ldate = uids.login_date
        now_time = datetime.datetime.now()
        if now_time - ldate > datetime.timedelta(minutes=5):
            user_json = CodeModeDTO(CodeModeDTO.PARAMETER_ERROR, 'code错误', '')
            return HttpResponse(user_json.to_json(), content_type='application/json,charset=utf-8')
    except Ucodes.DoesNotExist:
        user_json = CodeModeDTO(CodeModeDTO.PARAMETER_ERROR, 'code错误', '')
        return HttpResponse(user_json.to_json(), content_type='application/json,charset=utf-8')
    code = uids.u_code
    Ucodes.objects.get(u_code=ucode).delete()
    # 转化为实体
    uidss = model_to_dict(uids)
    uidss["code"] = code
    """
    规范接口返回格式 即CodeModeDTO（code,message,data）
     :param code: int 返回码
     :param message: string 返回消息
     :param data: obj 返回的数据
    """
    user_json = CodeModeDTO(CodeModeDTO.SUCCESS, '查询成功', uidss)
    return HttpResponse(user_json.to_json(), content_type='application/json,charset=utf-8')
